﻿using System;
using System.Globalization;
using System.Linq;
using System.Xml.Linq;

namespace System.Xml.Linq
{

    public static class XExtensions
    {
        
        public static TResult AttributeValue<TResult>(this XElement element, XName attributeName)
        {
            return AttributeValue<TResult>(element, attributeName, default(TResult));
        }

        public static TResult AttributeValue<TResult>(this XElement element, XName attributeName, TResult defaultValue)
        {
            XAttribute xAtt = element.Attribute(attributeName);

            if (xAtt == null)
            {
                return defaultValue;
            }

            Type t = typeof(TResult);
            if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                t = t.GetGenericArguments().FirstOrDefault();
            }

            try
            {
                var ret = Convert.ChangeType(xAtt.Value, t, CultureInfo.InvariantCulture);
                return (TResult)ret;
            }
            catch
            {
                return defaultValue;
            }
        }
        
    }

}